/**
 * Created by xiaogangzai on 2018/1/25.
 * 登录
 */
let connection = require('../../bin/api');
let sqlName = require('../../config/sqlname');
let sql = require('../../db/BlogSQL');
let tool = require('../../lib/utils/tool');
let config = require('../../config/dev');
var expires = 1000 * 60 * 60 * 24 * 15;
exports.login = function (req, res, next) {
    const username = req.body.username;
    const password = req.body.password;
    //先查询数据库中是否有用户名，有的话看密码是否相同,相同的话才可以登录
    connection.SelectData(sqlName.selectUsername, sql.login_select_username(username), function (err, result) {
            console.log(result);
            if (result == null) {
                console("检查1" + result)
                return res.json({code: -1, message: "清先注册"});
            } else {
                if (result.password == password) {
                    //tokenExpire
                    //token表中插入数据
                    var update = {
                        token: tool.encrypt(result.id + '\t' + (new Date().getTime()), config.authSecret),
                        tokenExpire: new Date(new Date().getTime() + expires).getTime()
                    }
                    connection.insertOne(sqlName.insertToken, sql.login_insert_token(result.id, result.createdOn, result.tokenType, token, result.userId, tokenExpire), function (err, result) {
                        console.log("token表插入成功");
                    })
                    return res.json({
                            code: 0,
                            message: {
                                user: {name: result.name, age: result.age, email: result.email, phone: result.phone},
                                token: {
                                    token: tool.encrypt(result.id + '\t' + (new Date().getTime()), config.authSecret),
                                    tokenExpire: new Date(new Date().getTime() + expires).getTime()
                                }
                            }
                        }
                    )


                }
            }
        }
    )
}